package com.lazydong.apiforward.client.gui.util;

import com.lazydong.apiforward.client.framework.PageContainer;
import com.lazydong.apiforward.client.framework.util.RunCmdUtil;
import com.lazydong.apiforward.client.gui.enums.PageEventEnum;

import java.awt.*;
import java.io.File;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;

public class WindowsUtil {
    public static void openBrowser(String url, String browserPath) {
        URI uri = getURI(url);
        if (browserPath == null) {
            try {
                Desktop.getDesktop().browse(uri);
            } catch (IOException e) {
                PageContainer.sendAsyncEvent(PageEventEnum.MAIN_PAGE_TIP, "打开浏览器失败");
            }
            return;
        }
        RunCmdUtil.runCmd("start " + browserPath + " \"" + url + "\"");
    }

    private static URI getURI(String path) {
        try {
            return new URI(path);
        } catch (URISyntaxException e) {
            File file = new File(path);
            if (file.exists() && file.isFile() && path.toLowerCase().endsWith(".html")) {
                return file.toURI();
            }
        }
        return null;
    }

    public static void openExe(File exe) {
        try {
            Desktop.getDesktop().open(exe);
        } catch (IOException e) {
            PageContainer.sendAsyncEvent(PageEventEnum.MAIN_PAGE_TIP, "打开软件失败");
        }
    }
}
